package com.hoshiicloud.auth.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @program: hoshiibuy
 * @description: 序列化工具类
 * @author: Mr.wu
 * @create: 2019-06-25 10:42
 **/
@Slf4j
public class SerializeUtil {

    /**
     * @param obj
     * @return byte[]
     * @author: Mr.wu
     * @descripton: 序列化对象
     * @date: 10:44 2019/6/25
     */
    public static byte[] ObjTOSerialize(Object obj){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream byteOut = null;
        try{
            byteOut = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(byteOut);
            oos.writeObject(obj);
            byte[] bytes = byteOut.toByteArray();
            return bytes;
        }catch (Exception e) {
            log.error("对象序列化失败");
        }
        return null;
    }

    /**
     * @param bytes
     * @return java.lang.Object
     * @author: Mr.wu
     * @descripton: 反序列化
     * @date: 10:43 2019/6/25
     */
    public static Object unSerialize(byte[] bytes){
        ByteArrayInputStream in = null;
        try{
            in = new ByteArrayInputStream(bytes);
            ObjectInputStream objIn = new ObjectInputStream(in);
            return objIn.readObject();
        }catch (Exception e) {
            log.error("反序列化失败");
        }
        return null;
    }
}
